package vsm.vsm_server.mapper;

import org.apache.ibatis.annotations.*;
import vsm.vsm_server.pojo.User.Record.History.CreateHistoryDTO;
import vsm.vsm_server.pojo.User.Record.History.HistoryVideo;
import vsm.vsm_server.pojo.User.Record.History.UserVideoHistoryDTO;

import java.math.BigInteger;
import java.util.List;

@Mapper
public interface HistoryMapper {


    @Select("select * from history where userid = #{userid} order by createTime DESC")
    List<HistoryVideo> getHistoryVideos(BigInteger userId);

    @Insert("INSERT INTO history (userId, videoId, currentTime, createTime, finished) " +
            "VALUES (#{userId}, #{videoId}, #{currentTime}, #{createTime}, #{finished}) " +
            "ON DUPLICATE KEY UPDATE " +
            "currentTime = VALUES(currentTime), " +
            "createTime = VALUES(createTime), " +
            "finished = GREATEST(finished, VALUES(finished))")
    void createOrUpdateHistory(CreateHistoryDTO historyVideo);

    @Select("select * from history where userid = #{userId} and videoid=#{videoId}")
    HistoryVideo getHistory(BigInteger userId, BigInteger videoId);

    @Select("select count(*) from history where videoid=#{videoId}")
    Double getViewCount(BigInteger videoId);


    @Select("""
            WITH RankedHistory AS (
                SELECT
                    userId,
                    videoId,
                    finished,
                    createTime,
                    ROW_NUMBER() OVER (PARTITION BY userId ORDER BY createTime DESC) as rn
                FROM
                    history
                -- 可选: WHERE createTime >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            )
            SELECT
                userId,
                videoId,
                finished
            FROM
                RankedHistory
            WHERE
                rn <= #{limit}
            ORDER BY
                userId, createTime DESC
            """)
    // 使用 @Results 进行列名到 DTO 属性名的映射 (如果列名和属性名不完全一致)
    @Results({
            @Result(property = "userId", column = "userId"),
            @Result(property = "videoId", column = "videoId"),
            @Result(property = "finished",column = "finished")
    })
    List<UserVideoHistoryDTO> getAllHistoryVideos(@Param("limit") int limit);

}
